import json
import re
from random import randint

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render

from django.views import View
from django_redis import get_redis_connection

from apps.users.models import User
from iHome.settings.dev import logger
from libs.captcha.captcha import captcha
from ronglian_sms_sdk import SmsSDK


# 图片验证码
class ImageCodeView(View):
    def get(self,request):
        # 提取参数
        uuid = request.GET.get('cur')
        last_uuid = request.GET.get('pre')
        print(uuid)
        # 校验参数:
        if uuid is None:
            return JsonResponse({'errno':4002,'errmsg':'缺少必传参数'})

        # 生成图片验证码
        text,image = captcha.generate_captcha()

        # 保存图片验证码到redis数据库
        client = get_redis_connection('verify_code')
        client.setex(f'img_{uuid}',300,text)

        return HttpResponse(image,content_type='image/jpg')


# 短信验证码
class SmsCodeView(View):
    def post(self,request):
        # 提取参数
        json_dict = json.loads(request.body)
        mobile = json_dict.get('mobile')
        # 用户输入的图片验证码
        image_code = json_dict.get('image_code')
        uuid = json_dict.get('image_code_id')

        # 校验参数
        if not all([mobile,image_code,uuid]):
            return JsonResponse({'errno':4002,'errmsg':'缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return JsonResponse({'errno':4004,'errmsg':'手机号格式错误'})


        # 创建链接redis数据库对象
        client = get_redis_connection('verify_code')
        # 避免频繁发送短信验证码
        send_flag = client.get(f'send_flag{mobile}')
        if send_flag:
            return JsonResponse({'errno':4003,'errmsg':'短信发送太频繁'})

        # 从数据库提取图片验证码并校验
        redis_image_code = client.get(f'img_{uuid}')
        if redis_image_code is None:
            # 图片验证码过期或者不存在
            return JsonResponse({'errno':4002,'errmsg':'验证码已失效'})
        # 删除图片验证码避免恶意测试
        try:
            client.delete(f'img_{uuid}')
        except Exception as e:
            logger.error(e)
        # 对比图片验证码
        # redis数据库取出的是二进制，须转换成字符串格式
        # 将验证码全都小写--不区分大小写
        if image_code.lower() != redis_image_code.decode().lower():
            return JsonResponse({'errno':4004,'errmsg':'验证码错误'})

        # 判断手机号是否重复注册
        try:
            user = User.objects.get(mobile=mobile)

        except Exception as e:
            user=None
            logger.error(e)

        if user:
            return JsonResponse({'errno':4003,'errmsg':'手机号已注册'})

        # 生成短信验证码
        sms_code = randint(100000,999999)
        print('短信验证码：',sms_code)

        # 保存短信验证码
        client.setex(f'sms_{mobile}',300,sms_code)
        client.setex(f'send_flag{mobile}',60,1)
        # 发送短信验证码
        # sdk = SmsSDK('8aaf0708697b6beb01699f54fc6317eb', '6e5*******1543', '8aaf0708697b6beb01699f54fcc517f2')
        # #                      短信模板,手机号,  ('短信内容',过期时间),
        # sdk.sendMessage('1', mobile, (sms_code, 5))
        # print('短信验证码:', sms_code)

        # 10. 响应结果
        return JsonResponse({'errno': 0,'errmsg': '发送短信成功'})
